import { Input, InputProps } from 'antd';
import { useEffect, useState, useCallback, ChangeEvent } from 'react';

export default function RegExpInput({
  value,
  reg,
  onChange,
  ...other
}: { value?: string; reg?: RegExp } & InputProps) {
  const [val, $val] = useState(value);
  useEffect(() => {
    $val(value);
  }, [value]);
  const handleChange = useCallback(
    (e: ChangeEvent<HTMLInputElement>) => {
      const value = e.target.value;
      if (reg) {
        if (reg.test(value) || value === '') {
          $val(value);
          onChange?.(e);
        }
      } else {
        $val(value);
        onChange?.(e);
      }
    },
    [reg],
  );

  return <Input {...other} value={val} onChange={handleChange} />;
}
